package com.yc.config;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.List;

@Component
public class PersistentChatMemoryStore implements ChatMemoryStore {

    //redis键值库,为了区分数据,设计键的前缀
    private static final String REDIS_KEY_PREFIX = "chat:memory";

    private RedisTemplate<String,String >  redisTemplate;

public PersistentChatMemoryStore(RedisTemplate<String,String > redisTemplate){
    this.redisTemplate=redisTemplate;
}

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        String key = getKey( memoryId);
            String messageJson = redisTemplate.opsForValue().get(key);
            if(messageJson==null || messageJson.isEmpty()){
                return List.of();
            }
            return ChatMessageDeserializer.messagesFromJson(messageJson);
    }

    private String getKey(Object memoryId) {
        return REDIS_KEY_PREFIX  + memoryId.toString();
    }

    @Override
    public void updateMessages(Object o, List<ChatMessage> list) {
        String key = getKey(o);
        String messageJson = ChatMessageSerializer.messagesToJson(list);
            redisTemplate.opsForValue().set(key,messageJson);

    }

    @Override
    public void deleteMessages(Object o) {
    this.redisTemplate.delete(getKey(o));

    }
    public void close(){
        redisTemplate.getConnectionFactory().getConnection().close();
    }
}
